from django.db import models
from django.contrib.auth.models import User
import os

class Ticket(models.Model):
    # 工单状态选择 - 完整的维修流程
    STATUS_CHOICES = (
        ('draft', '草稿'),
        ('applied', '维修申请'),
        ('registered', '登记签收'),
        ('assigned', '设备分配'),
        ('testing', '设备检测'),
        ('repairing', '设备维修'),
        ('quality_check', '维修质检'),
        ('completed', '维修完成待返还'),
        ('returned', '已返还'),
        ('terminated', '已终止'),  # 报废操作终止工单
    )
    
    # 优先级选择
    PRIORITY_CHOICES = (
        ('high', '高'),
        ('medium', '中'),
        ('low', '低'),
    )
    
    ticket_number = models.CharField(max_length=20, blank=True, verbose_name='工单号')
    title = models.CharField(max_length=200, verbose_name='工单标题')
    description = models.TextField(verbose_name='问题描述')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft', verbose_name='工单状态')
    priority = models.CharField(max_length=20, choices=PRIORITY_CHOICES, default='medium', verbose_name='优先级')
    
    # 关联关系
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='created_tickets', verbose_name='创建者')
    assigned_to = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, 
                                   related_name='assigned_tickets', verbose_name='分配给')
    assets = models.ManyToManyField('assets.Asset', blank=True, related_name='tickets', verbose_name='关联设备')
    
    # 时间信息
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    # 各阶段时间戳
    registered_at = models.DateTimeField(null=True, blank=True, verbose_name='登记时间')
    assigned_at = models.DateTimeField(null=True, blank=True, verbose_name='分配时间')
    testing_at = models.DateTimeField(null=True, blank=True, verbose_name='检测时间')
    repairing_at = models.DateTimeField(null=True, blank=True, verbose_name='维修时间')
    quality_check_at = models.DateTimeField(null=True, blank=True, verbose_name='质检时间')
    completed_at = models.DateTimeField(null=True, blank=True, verbose_name='完成时间')
    returned_at = models.DateTimeField(null=True, blank=True, verbose_name='返还时间')
    
    # 分配信息
    assigned_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True,
                                   related_name='assigned_by_tickets', verbose_name='分配人')
    assignment_notes = models.TextField(blank=True, verbose_name='分配备注')
    
    # 质检信息
    quality_check_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True,
                                       related_name='quality_checked_tickets', verbose_name='质检人')
    quality_notes = models.TextField(blank=True, verbose_name='质检备注')
    
    # 登记信息
    registered_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True,
                                    related_name='registered_tickets', verbose_name='登记人')
    
    # 完成信息
    completed_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True,
                                   related_name='completed_tickets', verbose_name='完成人')
    
    # 返还信息
    returned_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True,
                                  related_name='returned_tickets', verbose_name='返还人')
    
    class Meta:
        verbose_name = '维修工单'
        verbose_name_plural = '维修工单'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.ticket_number} - {self.title} - {self.get_status_display()}"

    def save(self, *args, **kwargs):
        if not self.ticket_number:
            self.ticket_number = self.generate_ticket_number()
        super().save(*args, **kwargs)

    def generate_ticket_number(self):
        """生成工单号: TKT-YYYYMMDD-序号"""
        from django.utils import timezone
        import datetime
        
        # 获取当前日期
        today = timezone.now().date()
        date_str = today.strftime("%Y%m%d")
        
        # 查找今天创建的工单数量
        today_start = datetime.datetime.combine(today, datetime.time.min)
        today_end = datetime.datetime.combine(today, datetime.time.max)
        
        today_tickets = Ticket.objects.filter(
            created_at__range=(today_start, today_end)
        ).exclude(ticket_number__isnull=True).exclude(ticket_number='')
        
        # 计算今天的序号
        sequence_number = today_tickets.count() + 1
        
        return f"TKT-{date_str}-{sequence_number:04d}"

class TicketImage(models.Model):
    """工单图片模型"""
    ticket = models.ForeignKey(
        Ticket, 
        on_delete=models.CASCADE, 
        related_name='images',
        verbose_name='关联工单'
    )
    image = models.ImageField(
        upload_to='ticket_images/%Y/%m/%d/',
        verbose_name='图片文件',
        help_text='支持JPG, PNG, GIF格式，单个文件不超过5MB'
    )
    description = models.CharField(
        max_length=200, 
        blank=True, 
        verbose_name='图片描述'
    )
    order = models.PositiveIntegerField(
        default=0, 
        verbose_name='排序序号'
    )
    uploaded_at = models.DateTimeField(
        auto_now_add=True, 
        verbose_name='上传时间'
    )
    file_size = models.PositiveIntegerField(
        default=0, 
        verbose_name='文件大小(字节)'
    )
    
    class Meta:
        verbose_name = '工单图片'
        verbose_name_plural = '工单图片'
        ordering = ['order', 'uploaded_at']
    
    def __str__(self):
        return f"{self.ticket.ticket_number} - 图片{self.order + 1}"
    
    def delete(self, *args, **kwargs):
        """删除模型时同时删除文件"""
        if self.image and os.path.isfile(self.image.path):
            try:
                os.remove(self.image.path)
            except:
                pass
        super().delete(*args, **kwargs)
    
    def save(self, *args, **kwargs):
        """保存时记录文件大小"""
        if self.image:
            self.file_size = self.image.size
        super().save(*args, **kwargs)

class MaintenanceRecord(models.Model):
    """维修记录"""
    ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, related_name='maintenance_records', verbose_name='工单')
    technician = models.ForeignKey(User, on_delete=models.CASCADE, related_name='maintenance_records', verbose_name='技术人员')
    description = models.TextField(verbose_name='维修描述')
    parts_used = models.TextField(blank=True, verbose_name='使用零件')
    hours_spent = models.DecimalField(max_digits=5, decimal_places=2, default=0, verbose_name='耗时(小时)')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='记录时间')
    
    class Meta:
        verbose_name = '维修记录'
        verbose_name_plural = '维修记录'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.ticket.title} - {self.technician.username}"
